/*
 * Copyright (C) 2015 truth
 *
 * This program is non-free software, but you can redistribute it and/or modify
 * it if you are in hjj(Huangshi Hejianjiao) team.
 */
package com.truthbean.jutils.web.filter;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.BasicConfigurator;

import com.truthbean.jutils.dao.utils.Connector;
import com.truthbean.jutils.dao.utils.DBContext;

/**
 * Servlet Filter implementation class TransactionFilter
 *
 * @since Jan 15, 2015 11:21:31 AM
 * @author TruthBean
 */
//@WebFilter(urlPatterns = "/*", filterName = "TransactionFilter", asyncSupported = true)
public class TransactionFilter implements Filter {

    /**
     * Default constructor.
     */
    public TransactionFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @param request
     * @param response
     * @param chain
     * @throws java.io.IOException
     * @throws javax.servlet.ServletException
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        Connection connection = null;
        try {
            //1. 获取连接
            connection = Connector.getConn();
            //2. 开启事务
            connection.setAutoCommit(false);
            //3. 利用 ThreadLocal 把连接和当前线程绑定
            DBContext.getInstance().bind(connection);
            //4. 把请求转给 Servlet
            chain.doFilter(request, response);
            //5. 提交事务
            connection.commit();
        } catch (SQLException | IOException | ServletException e) {
            Logger.getLogger(TransactionFilter.class.getName()).log(Level.SEVERE, null, e);
            //6. 回滚事务
            try {
                if (connection != null) {
                    connection.rollback();
                }
            } catch (SQLException e1) {
                Logger.getLogger(TransactionFilter.class.getName()).log(Level.SEVERE, "事务回滚失败", e1);
            }
            HttpServletResponse resp = (HttpServletResponse) response;
            HttpServletRequest req = (HttpServletRequest) request;
            resp.sendRedirect(req.getContextPath() + "/error/500.html");
        } finally {
            //7. 解除绑定
            if (DBContext.getInstance() != null) {
                DBContext.getInstance().remove();
            }
            //8. 关闭连接
            Connector.release(connection);

        }
    }

    /**
     * @param fConfig
     * @throws javax.servlet.ServletException
     * @see Filter#init(FilterConfig)
     */
    @Override
    public void init(FilterConfig fConfig) throws ServletException {
        BasicConfigurator.configure();
    }

}
